/**
 *
 */
package net.haroeris.wh40kcampaign.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;

import net.haroeris.wh40kcampaign.beans.po.Player;
import net.haroeris.wh40kcampaign.beans.to.PlayerTO;
import net.haroeris.wh40kcampaign.dao.Authorities;
import net.haroeris.wh40kcampaign.dao.PlayerDao;
import net.haroeris.wh40kcampaign.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Service;

/**
 * @author user
 *
 */
@Service("userService")
public class UserServiceImpl implements UserService {

	@Autowired
	private PlayerDao playerDao;

	@Autowired
	@Qualifier("userDetailsManager")
	private UserDetailsManager userDetailsManager;

	/* (non-Javadoc)
	 * @see net.haroeris.wh40kcampaign.service.UserService#getAllPlayers()
	 */
	public Collection<PlayerTO> getAllPlayers() {
		Collection<Player> allPlayerPOs= playerDao.getAllPlayers();

		Collection<PlayerTO> allPlayers= new ArrayList<PlayerTO>(allPlayerPOs.size());
		for( Player playerPo :  allPlayerPOs ){
			allPlayers.add( new PlayerTO(playerPo) );
		}
		return allPlayers;
	}

	/* (non-Javadoc)
	 * @see net.haroeris.wh40kcampaign.service.UserService#getPlayerByUsername(java.lang.String)
	 */
	public PlayerTO getPlayerByUsername(String username) {
		Player player= playerDao.getPlayerByUsername(username);
		if( player!=null ){
			return new PlayerTO(player);
		} else {
			return null;
		}
	}

	/* (non-Javadoc)
	 * @see net.haroeris.wh40kcampaign.service.UserService#createPlayer(net.haroeris.wh40kcampaign.beans.to.PlayerTO, java.lang.String)
	 */
	public boolean createPlayer(PlayerTO newPlayer, String password) {

		Collection<GrantedAuthority> authorithies= new HashSet<GrantedAuthority>(1);

		authorithies.add(new SimpleGrantedAuthority(Authorities.Users.getAuthority()));

		UserDetails userDetails= new User( newPlayer.getName(), password, authorithies );
		userDetailsManager.createUser(userDetails);
		return true;
	}

	/* (non-Javadoc)
	 * @see net.haroeris.wh40kcampaign.service.UserService#deletePlayer(net.haroeris.wh40kcampaign.beans.to.PlayerTO)
	 */
	public boolean deletePlayer(PlayerTO player) {
		userDetailsManager.deleteUser(player.getName());
		return true;
	}


}